<?php
/**
 * CourseType Model
 * 
 * @package    	ReportManager
 * @author		Internet Apps Development Course
 * @copyright	
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class ReportManagerModelCourseType extends JModel
{
	function __construct()
	{
		parent::__construct();
		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	
		$table_path = 'components/com_reportmanager/tables'; 
		$this->addTablePath($table_path);
	}

	function setId($id)
	{
		$this->_id		= $id;
		$this->_data	= null;
	}

	function &getData()
	{
		if ($this->_id > 0) {
			$query = ' SELECT ct.id, ct.name, ct.user_id '.
						' FROM #__RM_CourseType as ct '.
						' where ct.id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		} else {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->name = null;
		}
		
		return $this->_data;
	}
	
	function getList()
	{
		$query = ' SELECT ct.id, ct.name, ct.user_id , u.name as user_name '.
						' FROM #__RM_CourseType as ct, #__users as u '.
						' where ct.user_id = u.id ';
						' ORDER BY ct.name ';
		$this->_db->setQuery( $query );
		$this->_data = $this->_getList( $query );
		return $this->_data;
	}


	function store()
	{	
		$row =& $this->getTable( 'coursetype' );
		$data = JRequest::get( 'post' );
		$user =& JFactory::getUser();
		$data[user_id] = $user->get('id');
		
		/*
		 *  Check if the user is registered
		 */
		$groups = $user->getAuthorisedGroups();
		$registered = false;
		$query = ' SELECT groups.id FROM #__usergroups as groups WHERE groups.title = "Registered" ';
		$this->_db->setQuery( $query );
		$reg_group_id = $this->_db->loadObject();
		for ($i = 0; $i < count($groups); $i++) {
			if ($groups[$i] == $reg_group_id->id) {
				$registered = true;
			}
		}
		if ($registered == false) {
			return false;
		}
		
		/*
		 *  Check if user is the author of content
		 */
		$query = ' SELECT ct.user_id FROM #__RM_CourseType as ct WHERE ct.id = '.$data[id];
		$this->_db->setQuery( $query );
		$usr_id = $this->_db->loadObject();
		if ($usr_id->user_id != $data[user_id] && $usr_id->user_id > 0) {
			return false;
		}
		
		
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
				
		return true;
	}
}